<template>
    <div style="float: right;">
        <el-select v-model="language" placeholder="语言" @change="il8n.global.locale.value = language" style="width: 240px">
            <el-option v-for="item in [{
                value: 'zhCn',
                label: '中文',
            },
            {
                value: 'en',
                label: '英语',
            },
            {
                value: 'ja',
                label: '日语',
            }
            ]" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
    </div>
    <div class='w-full h-full flex items-center justify-center bg-[#ccc]'>
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <el-form-item :label="$t('login.username')" prop="username">
                <el-input v-model="ruleForm.username" autocomplete="on" :placeholder="$t('login.username')" />
            </el-form-item>
            <el-form-item :label="$t('login.password')" prop="password">
                <el-input v-model="ruleForm.password" type="password" autocomplete="off"
                    :placeholder="$t('login.password')" />
            </el-form-item>
            <el-form-item :label="$t('login.captcha')" prop="captcha">
                <el-input v-model="ruleForm.captcha" :placeholder="$t('login.captcha')" />
                <el-tag><img :src="captchaImg.src" alt=""></el-tag>
            </el-form-item>
            <el-form-item>
                <div class="flex w-full justify-between">
                    <el-checkbox v-model="autoLogin" :label="$t('login.autologin')"></el-checkbox>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button class="w-full" type="primary" @click="submitForm(ruleFormRef)">
                    {{ $t('login.login') }}
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { loginApi, getCaptchaApi } from '@/api/login'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { il8n } from './locales/index'
import { ElNotification } from 'element-plus'

const language = ref<'zhCn' | 'en' | 'ja'>('zhCn')


const router = useRouter()

const captchaImg = reactive<Record<string, string>>({})
const ruleFormRef = ref<FormInstance>()

const checkPass = (rule: unknown, value: string, callback: (error?: Error) => void) => {
    if (value.trim()) {
        callback()
    } else {
        callback(new Error('请输入密码'))
    }
}

const checkCaptcha = (rule: unknown, value: string, callback: (error?: Error) => void) => {
    if (value.trim()) {
        callback()
    } else {
        callback(new Error('请输入验证码'))
    }
}
const checkUsername = (rule: unknown, value: string, callback: (error?: Error) => void) => {
    if (value.trim()) {
        callback()
    } else {
        callback(new Error('请输入用户名'))
    }
}

const ruleForm = reactive({
    captcha: '',
    username: '',
    password: '',
    captcha_id: '',
    captcha_code: '',
})

const autoLogin = ref(false)

const getCaptcha = () => {

    let timer: number | undefined

    return () => getCaptchaApi().then((res: any) => {
        captchaImg.src = res.data.image
        captchaImg.id = res.data.id

        if (timer) {
            clearTimeout(timer)
        }

        timer = setTimeout(() => {
            getCaptcha()()
        }, res.data.expires_in * 1000)
    })
}


const rules = reactive<FormRules<typeof ruleForm>>({
    captcha: [{ validator: checkCaptcha, trigger: 'blur' }],
    username: [{ validator: checkUsername, trigger: 'blur' }],
    password: [{ validator: checkPass, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            loginApi({
                username: ruleForm.username,
                password: ruleForm.password,
                captcha_id: captchaImg.id!,
                captcha_code: ruleForm.captcha,
            }).then((res: any) => {
                if (res.code === 200) {
                    localStorage.setItem('login', JSON.stringify(res.data))
                    router.replace('/NewsPool')
                }
                if (res.code !== 200) {
                    getCaptcha()()
                    ElNotification.error({
                        title: '登录失败',
                        message: res.data.message,
                    })
                }
            }).catch((error) => {
                getCaptcha()()
            })
        } else {
            console.log('error submit!')
        }
    })
}

onMounted(() => {
    getCaptchaApi().then((res: any) => {
        captchaImg.src = res.data.image
        captchaImg.id = res.data.id


        setTimeout(() => {
            getCaptcha()()
        }, res.data.expires_in * 1000)
    })
})



</script>

<style scoped>
.demo-ruleForm {
    min-width: 30%;
}
</style>
